﻿using System;
using System.Windows.Forms;

namespace ShareHelper
{
    /// <summary>
    /// 定时启动类
    /// </summary>
    public class TimingStart
    {
        /// <summary>
        /// 启动时间设置控件
        /// </summary>
        private DateTimePicker Date { get; }

        /// <summary>
        /// 定时启动类
        /// </summary>
        /// <param name="dateTimePicker">定时设置组建</param>
        public TimingStart(DateTimePicker dateTimePicker)
        {
            Date = dateTimePicker;
            dateTimePicker.Format = DateTimePickerFormat.Custom;
            dateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm";
            dateTimePicker.Width = 140;
            Timer = new TimerEx(100, 1000);
            Timer.Elapsed += Timer_Elapsed;
        }

        /// <summary>
        /// 回调函数
        /// </summary>
        private Action CallBack;

        /// <summary>
        /// 定时器
        /// </summary>
        private TimerEx Timer { get; }

        /// <summary>
        /// 启动定时启动
        /// </summary>
        /// <param name="action">启动回调函数</param>
        public bool Start(Action action)
        {
            if (Date?.IsDisposed == false)
            {
                StartDate = Date.Value;
                if (StartDate > DateTime.Now)
                {
                    CallBack = action;
                    Timer.Start();
                    return true;
                }
                else Log.Info("启动时间必须大于,现行时间");
            }
            else Log.Info("定时组件不存在");
            return false;
        }

        /// <summary>
        /// 启动是间
        /// </summary>
        private DateTime StartDate;

        private void Timer_Elapsed(object state)
        {
            var date = StartDate - DateTime.Now;
            var time = date.TotalSeconds;
            if (time > 0)
            {
                int Period, interval;
                Period = interval = Timer.Period;
                if (time < 120)
                    interval = 1000 * 10;
                else if (time < 20)
                    interval = 1000;
                if (interval != Period)
                    Timer.Period = interval;
                Log.Debug($"倒计时:{date:d'天'h'时'm'分's'秒'}");
            }
            else
            {
                //释放时钟资源
                Timer.Dispose();
                CallBack.Invoke();
            }
        }
    }
}